package com.eascs.continueloan.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.eascs.app.dao.PageResult;
import com.eascs.app.dao.SqlPageQuery;
import com.eascs.common.util.StringUtil;
import com.eascs.continueloan.dao.O2OContinueLoanDao;
import com.eascs.continueloan.entity.O2oContinueFormEntity;
import com.eascs.continueloan.entity.O2oUpdateLoanEntity;

@Service
public class O2oContinueLoanService {

	@Autowired
	O2OContinueLoanDao o2oContinueLoanDao;
	
	public PageResult<Object[]> findO2oByPage(O2oContinueFormEntity entity){
		SqlPageQuery<Object[]> sqlPageQuery = new SqlPageQuery<>(Object[].class, entity.getPageSize(), entity.getO2oIndex());
		StringBuffer querySql = new StringBuffer();
		querySql.append(" SELECT OL.BILL_CODE AS BILLCODE,OLU.USER_FULL_NAME,CONCAT(LEFT (OLU.DOCUMENT_NO, 3) ");
		querySql.append(" ,'****',RIGHT (OLU.DOCUMENT_NO, 3)) as DOCUMENT_NO,OL.OPERATOR_NAME ");
		querySql.append(" ,CONCAT(OL.LTD_CODE,'-',OL.LTD_NAME) LTD_NAME,OL.LOAN_TYPE,OL.WF_TYPE ");
		querySql.append(" FROM O2O_LOANAPPLY OL JOIN O2O_LOAN_USER OLU ON  OLU.loanapply_no = OL.loanapply_no ");
		querySql.append(" and sponsor_type is null and spouse_id is null ");
		querySql.append(" WHERE /**DATA_PERMISSION(OL.LTD)**/ OL.WF_TYPE IN ('O','HN','YQ','DC')  AND ");
		querySql.append(" OL.LOAN_FLG='Y' and OL.loan_type not in ('FQ','EA')  ");
		querySql.append(" and OL.payment_time = (SELECT max(ol2.payment_time) from  ");
		querySql.append(" o2o_loanapply ol2 where OL2.WF_TYPE IN ('O','HN','YQ','DC')  AND ");
		querySql.append(" OL2.LOAN_FLG='Y' and OLU.loan_id=ol2.loan_id GROUP BY ol2.loan_id ) ");
		if(!StringUtil.isEmpty(entity.getUserName())){
			querySql.append(" AND OLU.USER_FULL_NAME LIKE ? ");
			sqlPageQuery.addLikeParam(entity.getUserName());
		}
		if(!StringUtil.isEmpty(entity.getUserIdCard())){
			querySql.append(" AND OLU.DOCUMENT_NO LIKE ? ");
			sqlPageQuery.addLikeParam(entity.getUserIdCard());
		}
		if(!StringUtil.isEmpty(entity.getBillCode())){
			querySql.append(" AND OL.BILL_CODE LIKE ? ");
			sqlPageQuery.addLikeParam(entity.getBillCode());
		}
		//querySql.append(" GROUP BY OL.LOANAPPLY_NO ");
		sqlPageQuery.setQuerySql(querySql.toString());
		return o2oContinueLoanDao.findDataWithPage(sqlPageQuery);
	}
	
	public int updateContinueLoan(O2oUpdateLoanEntity entity){
		return o2oContinueLoanDao.updateById(entity);
	}
}
